﻿layui.use(['element', 'layer', 'util','dropdown', 'comment'], function () {
    var element = layui.element
        , layer = layui.layer
        , util = layui.util
        , comment = layui.comment
        , dropdown = layui.dropdown
        , $ = layui.$;

    /**
     * 获取当前登录用户 
     * */
    comment._ACP(ApiUrl.Home.homeCurrentUserGet, {}, function (res) {
        if (res.success) {
            window.localStorage.setItem("currentUser", JSON.stringify(res.result));
            $('#user_name').text(res.result.name);
        } else {
            layer.msg(res.errorMsg);
            setTimeout(function () {
                window.localStorage.removeItem("token");
                window.location.href = login;
            }, 1000)
        }
    })

    /**
     * 获取当前登录用户菜单信息
     * 生成菜单
     * */
    comment._ACP(ApiUrl.LanbtPower.getMenuList, {}, function (res) {
        if (res.success) {
            var menuList = res.result;
            let html = '';
            if (menuList.length > 0) {
                html += '<ul class="layui-nav layui-nav-tree" lay-filter="lanbt-menu" lay-shrink="all" >';
                menuList.forEach(function (val, i) {
                    html += '<li class="layui-nav-item">';
                    //文件夹
                    if (val.powerType == 1) {
                        html += '<a href="javascript:;" data-icon="' + val.icon + '" ><i class="layui-icon ' + val.icon + '">&nbsp;' + val.title + '</i></a>';
                    }
                    //页面
                    else {
                        html += '<a class="nav-link text-dark lanbt-nav lanbt-menu" data-icon="' + val.icon + '" data-url="' + val.src + '" data-title="' + val.title + '" data-id="' + val.id + '" ><i class="layui-icon ' + val.icon + '">&nbsp;' + val.title + '</i></a>';
                    }
                    if (val.childrens.length > 0) {
                        html = RecursionMenu(html, val.childrens);
                    }
                    html += "</li>";
                })
                html += '</ul>'
            }
            $('.layui-side-scroll').append(html);
            element.render('nav');
        } else {
            layer.msg(res.errorMsg);
        }
    })

    /**
     * 无限极菜单
     * */
    function RecursionMenu(html, menuList) {
        html += '<ul class="layui-nav-child">'
        menuList.forEach(function (val, i) {
            html += '<li  class="layui-nav-item">';
            //文件夹
            if (val.powerType == 1) {
                html += '<a href="javascript:;" data-icon="' + val.icon + '" ><i class="layui-icon ' + val.icon + '">&nbsp;' + val.title + '</i></a>';
            }
            //页面
            else {
                html += '<a class="nav-link text-dark lanbt-nav lanbt-menu" data-icon="' + val.icon + '" data-url="' + val.src + '" data-title="' + val.title + '" data-id="' + val.id + '" ><i class="layui-icon ' + val.icon + '">&nbsp;' + val.title + '</i></a>';
            }
            if (val.childrens.length > 0) {
                RecursionMenu(html, val.childrens);
            }
            html += "</li>";
        })
        html += '</ul>'
        return html;
    }

    //头部事件
    util.event('lay-header-event', {
        //右侧菜单事件
        menuRight: function () {
            layer.open({
                type: 1
                , content: '<div style="padding: 15px;">处理右侧面板的操作</div>'
                , area: ['260px', '100%']
                , offset: 'rt' //右上角
                , anim: 5
                , shadeClose: true
                , move: false
            });
        }
    });

    var tab_ids = []
        , home_id = '';

    /*
     * 点击菜单添加tab 
     * */
    $(".lanbt-nav").click(function () {
        let id = $(this).data().id;
        if (tab_ids.indexOf(id) == -1) {
            let src = $(this).data().url;
            let title = $(this).data().title;
            let icon = $(this).data().icon;
            element.tabAdd('lanbt-tab', {
                title: '<i class="layui-icon ' + icon + '" style="font-size:14px" >&nbsp;' + title + '</i>',
                content: '<iframe class="i_body" src="' + src + '" width="100%" height="300" frameborder="no" scrolling="yes" allowtransparency="yes"></iframe>',
                id: id
            });
            tab_ids.push(id);
            i_body_height(".i_body")
        }
        element.tabChange('lanbt-tab', id)
        fnDropDownRolad();
    })

    /**
     * 生成菜单后，搜索【首页】菜单并点击，生成Tab选项卡，之后隐藏关闭按钮
     * */
    if ($('[data-url="/Home/Index"]').length > 0) {
        var home = $('[data-url="/Home/Index"]')[0];
        home.click();
        let id = $(home).data().id;
        var tab = $('[lay-id="' + id + '"] i')[1];
        $(tab).hide();
        home_id = id;
    }

    /**
     * Tab菜单加载
     * */
    function fnDropDownRolad() {
        dropdown.render({
            elem: '.layui-this' //在 id="demo" 的元素中触发事件。也可以直接设置为 document，从而重置整个右键菜单
            , trigger: 'contextmenu' //右键事件
            , data: [{
                title: '关闭'
                , id: 'close'
            }, {
                title: '关闭全部Tab'
                , id: 'close_all'
            }, {
                title: '关闭其他Tab'
                , id: 'close_other'
            }]
            , click: function (data, othis) {
                var tabId = this.elem.attr('lay-id'); //表格列表的预埋数据
                let ids = [];
                switch (data.id) {
                    case 'close':
                        if (tabId.indexOf(home_id) == -1) {
                            element.tabDelete('lanbt-tab', tabId);
                        }
                        break;
                    case 'close_all':
                        ids = $.extend(true, [], tab_ids);//深拷贝
                        ids.forEach(function (val) {
                            if (val.indexOf(home_id) == -1) {
                                element.tabDelete('lanbt-tab', val);
                            }
                        })
                        break;
                    case 'close_other':
                        ids = $.extend(true, [], tab_ids);//深拷贝
                        ids.forEach(function (val, i) {
                            if (val.indexOf(home_id) == -1 && val.indexOf(tabId) == -1) {
                                element.tabDelete('lanbt-tab', val);
                            }
                        });
                        break;
                    default:
                        
                        break;
                }
            }
        });
    }

    /**
     * 监听tab选项卡删除
     * */
    element.on('tabDelete(lanbt-tab)', function (data) {
        tab_ids.splice(data.index, 1);
    });
    /**
     * 监听Tab选项卡切换
     * 切换tab，侧边导航跟随选择
     * */
    element.on('tab(lanbt-tab)', function (data) {
        const str = $(this).text();
        $('.layui-this').removeClass('layui-this');//移除所有选中样式
        var menu = $($('[data-title=' + $.trim(str) + ']')[0].parentElement);
        if (menu[0].children[0].className.indexOf('lanbt-menu') > -1) {
            menu.addClass("layui-this");//添加菜单选中
            var menuUl = menu[0].parentElement.parentElement;
            if (menuUl && menuUl.classList.value.indexOf("layui-nav-itemed") == -1) {
                $('.layui-nav-itemed').removeClass('layui-nav-itemed');
                $(menuUl).addClass("layui-nav-itemed")
            }
        }
        $(this).addClass("layui-this");//添加tab选中
    });

    /** 
     * Iframe 加载 
     * */
    $(".i_body").load(function () {
        i_body_height(this)
    })

    /**
     * 监听网页窗口变化
     * */
    window.addEventListener('resize', function () {
        i_body_height(".i_body")
        //监听退出全屏事件
        if (document.body.scrollHeight === window.screen.height && document.body.scrollWidth === window.screen.width) {
            //全屏状态
            $('.quanping').removeClass('icon-quanping').addClass('icon-quxiaoquanping');
            $('.quanping').attr('title', '取消全屏');
        } else {
            //要执行的动作
            $(".quanping").removeClass('icon-quxiaoquanping').addClass('icon-quanping');
            $('.quanping').attr('title', '全屏');
        }
    })

    /**
     * 窗口高度自适应
     * */
    function i_body_height(id) {
        let h = $('.layui-tab').height() - $('layui-tab-title').height();
        $('.layui-tab-content').attr("height", h);
        $('.layui-tab-item').attr("height", h);
        $(id).attr("height", h - 40);
    }

    $('#lock').click(function () {

        comment._ACP(ApiUrl.Config.GetUserConfig, {key:1}, function (res) {
            if (res.success) {
                if (!res.result) {
                    layer.msg("请去【设置】界面设置“锁屏密码”")
                    return;
                }
                var setting = JSON.parse(res.result);
                if (!setting['screen_password'] || setting['screen_password'].length == 0) {
                    layer.msg("请去【设置】界面设置“锁屏密码”")
                    return;
                }
                window.localStorage.setItem("lock", true);
                layer.open({
                    type: 1,
                    title: '锁屏中,请输入解锁密码',
                    content: '<input class="layui-input" style="width:250px;margin:4px auto;" type="password" id="pwd" />',
                    scrollbar: false,
                    resize: false,
                    move:false,
                    skin: 'layui-layer-lan',
                    closeBtn: 0,
                    shade: 1,
                    anim: 6,
                    area: [300, 150],
                    btn: ['确认'],
                    yes: function (index) {
                        var pass = $('#pwd').val();
                        comment._ACP(ApiUrl.Home.Unlock, { pass: pass }, function (res) {
                            if (res.success) {
                                window.localStorage.setItem("lock", false);
                                layer.close(index);
                            } else {
                                layer.msg(res.errorMsg, { icon: 2, time: 1000, offset: '100px', });
                            }
                        })
                    }
                })
            } else {
                comment.Error(res.errorMsg);
            }
        })
    })

    if (window.localStorage.getItem("lock") == 'true') {
        $('#lock').click();
    }

    //全屏事件
    $('#full-screen').click(function () {
        var element = document.documentElement;	
        if ($('.quanping').hasClass('icon-quanping')) {
            // 判断浏览器设备类型
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {	// 兼容火狐
                element.mozRequestFullScreen();
            } else if (element.webkitRequestFullscreen) {	// 兼容谷歌
                element.webkitRequestFullscreen();
            } else if (element.msRequestFullscreen) {	// 兼容IE
                element.msRequestFullscreen();
            }
        } else {
            //退出全屏
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        }
    });

    /**
     * 退出登录
     * */
    $("#output").click(function () {
        comment._ACP(ApiUrl.Home.signOut, {}, function (res) {
            if (res.success) {
                layer.msg('即将退出~');
                setTimeout(function () {
                    window.localStorage.removeItem("token");
                    window.localStorage.removeItem("currentUser");
                    window.location.href = login;
                }, 1000)
            } else {
                comment.Error(res.errorMsg);
            }
        });
    })

});